<template>
   <el-dialog 
    v-model="outerVisible" 
    title="插入对象" 
    width="800"
    class="custom-dialog"
  >
    <div class="dialog-buttons">
      <el-button class="icon-button" @click="openSatelliteDialog">
        <div class="button-icon">
          <el-icon size="24"><Cpu /></el-icon>
        </div>
        <span>卫星</span>
      </el-button>
      
      <el-button class="icon-button" @click="openGroundStationDialog">
        <div class="button-icon">
          <el-icon size="24"><OfficeBuilding /></el-icon>
        </div>
        <span>地面站</span>
      </el-button>
      
      <el-button class="icon-button" @click="openPointTargetDialog">
        <div class="button-icon">
          <el-icon size="24"><Location /></el-icon>
        </div>
        <span>地面目标</span>
      </el-button>
      
      <el-button class="icon-button" @click="openAreaTargetDialog">
        <div class="button-icon">
          <el-icon size="24"><MapLocation /></el-icon>
        </div>
        <span>地面区域目标</span>
      </el-button>
      
      <el-button class="icon-button" @click="openPayloadDialog">
        <div class="button-icon">
          <el-icon size="24"><Cpu /></el-icon>
        </div>
        <span>载荷</span>
      </el-button>
    </div>
    
    <el-dialog
      v-model="satelliteVisible"
      width="600"
      title="卫星信息"
      append-to-body
    >
      <el-form :model="satelliteForm" label-width="120px">
        <el-form-item label="卫星名称" prop="name">
          <el-input v-model="satelliteForm.name" placeholder="请输入卫星名称"/>
        </el-form-item>
        
        <el-form-item label="卫星定义">
          <el-select v-model="satelliteForm.definition" placeholder="请选择卫星定义">
            <el-option label="低轨卫星" value="leo"/>
            <el-option label="中轨卫星" value="meo"/>
            <el-option label="高轨卫星" value="geo"/>
          </el-select>
        </el-form-item>

        <el-form-item label="外推模型">
          <el-select v-model="satelliteForm.model" placeholder="请选择外推模型">
            <el-option label="SGP4" value="sgp4"/>
            <el-option label="数值积分" value="numeric"/>
          </el-select>
        </el-form-item>

        <el-form-item label="轨道信息">
          <el-input 
            v-model="satelliteForm.orbit" 
            type="textarea" 
            :rows="3"
            placeholder="请输入TLE格式轨道信息或JSON格式轨道参数"/>
        </el-form-item>

        <el-form-item label="姿态信息">
          <el-input
            v-model="satelliteForm.attitude"
            type="textarea"
            :rows="2"
            placeholder="请输入姿态参数(JSON格式)"/>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="satelliteVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSatellite">保存</el-button>
      </template>
    </el-dialog>

    <!-- Ground Station Dialog -->
    <el-dialog
      v-model="groundStationVisible"
      width="600"
      title="地面站信息"
      append-to-body
    >
      <el-form :model="groundStationForm" label-width="120px">
        <el-form-item label="地面站名称" prop="name">
          <el-input v-model="groundStationForm.name" placeholder="请输入地面站名称"/>
        </el-form-item>
        
        <el-form-item label="位置坐标">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input-number v-model="groundStationForm.longitude" :min="-180" :max="180" :step="0.0001"/>
              <span class="form-unit">经度</span>
            </el-col>
            <el-col :span="12">
              <el-input-number v-model="groundStationForm.latitude" :min="-90" :max="90" :step="0.0001"/>
              <span class="form-unit">纬度</span>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="海拔高度(m)">
          <el-input-number v-model="groundStationForm.height" :min="0" :step="1"/>
        </el-form-item>

        <el-form-item label="天线参数">
          <el-input
            v-model="groundStationForm.antenna"
            type="textarea"
            :rows="2"
            placeholder="请输入天线参数(JSON格式)"/>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="groundStationVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGroundStation">保存</el-button>
      </template>
    </el-dialog>

    <!-- Area Target Dialog -->
    <el-dialog
      v-model="areaTargetVisible"
      width="700"
      title="地面区域目标"
      append-to-body
    >
      <el-form :model="areaTargetForm" label-width="120px">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="areaTargetForm.name" placeholder="请输入区域名称"/>
        </el-form-item>
        
        <el-form-item label="边界点坐标">
          <el-table :data="areaTargetForm.points" border style="width: 100%">
            <el-table-column prop="longitude" label="经度" width="180">
              <template #default="{row}">
                <el-input-number 
                  v-model="row.longitude" 
                  :min="-180" :max="180" 
                  :step="0.0001"
                  controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column prop="latitude" label="纬度" width="180">
              <template #default="{row}">
                <el-input-number 
                  v-model="row.latitude" 
                  :min="-90" :max="90" 
                  :step="0.0001"
                  controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{index}">
                <el-button 
                  type="danger" 
                  size="small"
                  @click="removeAreaPoint(index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button 
            type="primary" 
            size="small" 
            @click="addAreaPoint"
            style="margin-top: 10px"
          >添加点</el-button>
        </el-form-item>

        <el-form-item label="区域颜色">
          <el-color-picker v-model="areaTargetForm.color"/>
        </el-form-item>

        <el-form-item label="区域说明">
          <el-input
            v-model="areaTargetForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入区域说明"/>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="areaTargetVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAreaTarget">保存</el-button>
      </template>
    </el-dialog>

    <!-- Point Target Dialog -->
    <el-dialog
      v-model="pointTargetVisible"
      width="600"
      title="地面目标"
      append-to-body
    >
      <el-form :model="pointTargetForm" label-width="120px">
        <el-form-item label="目标名称" prop="name">
          <el-input v-model="pointTargetForm.name" placeholder="请输入目标名称"/>
        </el-form-item>
        
        <el-form-item label="位置坐标">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input-number v-model="pointTargetForm.longitude" :min="-180" :max="180" :step="0.0001"/>
              <span class="form-unit">经度</span>
            </el-col>
            <el-col :span="12">
              <el-input-number v-model="pointTargetForm.latitude" :min="-90" :max="90" :step="0.0001"/>
              <span class="form-unit">纬度</span>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="海拔高度(m)">
          <el-input-number v-model="pointTargetForm.height" :min="0" :step="1"/>
        </el-form-item>

        <el-form-item label="目标类型">
          <el-select v-model="pointTargetForm.type" placeholder="请选择目标类型">
            <el-option label="军事目标" value="military"/>
            <el-option label="民用目标" value="civilian"/>
            <el-option label="基础设施" value="infrastructure"/>
          </el-select>
        </el-form-item>

        <el-form-item label="目标说明">
          <el-input
            v-model="pointTargetForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入目标说明"/>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="pointTargetVisible = false">取消</el-button>
        <el-button type="primary" @click="savePointTarget">保存</el-button>
      </template>
    </el-dialog>

    <!-- Payload Dialog -->
    <el-dialog
      v-model="payloadVisible"
      width="600"
      title="载荷信息"
      append-to-body
    >
      <el-form :model="payloadForm" label-width="120px">
        <el-form-item label="载荷名称" prop="name">
          <el-input v-model="payloadForm.name" placeholder="请输入载荷名称"/>
        </el-form-item>
        
        <el-form-item label="所属卫星">
          <el-select 
            v-model="payloadForm.satelliteId" 
            placeholder="请选择所属卫星"
            filterable
          >
            <el-option
              v-for="sat in JSON.parse(safeLocalStorage.getItem('satellites') || '[]')"
              :key="sat.id || sat.name"
              :label="sat.name"
              :value="sat.id || sat.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="载荷类型">
          <el-select v-model="payloadForm.type" placeholder="请选择载荷类型">
            <el-option
              v-for="type in payloadTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="视场类型">
          <el-select v-model="payloadForm.fovType" placeholder="请选择视场类型">
            <el-option
              v-for="type in fovTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="半锥角(度)">
          <el-input-number 
            v-model="payloadForm.halfAngle" 
            :min="1" 
            :max="180"
            :step="1"
          />
        </el-form-item>

        <el-form-item label="载荷描述">
          <el-input
            v-model="payloadForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入载荷描述"/>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="payloadVisible = false">取消</el-button>
        <el-button type="primary" @click="savePayload">保存</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
//使用layout的小仓库
import useLayOutSettingStore from '@/store/modules/setting'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  OfficeBuilding,
  Location,
  MapLocation,
  Cpu
} from '@element-plus/icons-vue'

const layoutSettingStore = useLayOutSettingStore()

// Safe localStorage access utility
const safeLocalStorage = {
  getItem: (key) => {
    try {
      return localStorage.getItem(key)
    } catch (e) {
      console.error('localStorage access error:', e)
      return null
    }
  },
  setItem: (key, value) => {
    try {
      localStorage.setItem(key, value)
    } catch (e) {
      console.error('localStorage access error:', e)
    }
  }
}

const outerVisible = ref(false)
const satelliteVisible = ref(false)
const groundStationVisible = ref(false)
const satelliteForm = ref({
  name: '',
  definition: '',
  model: '',
  orbit: '',
  attitude: ''
})
const groundStationForm = ref({
  name: '',
  longitude: 116.4,
  latitude: 39.9,
  height: 0,
  antenna: ''
})

const openSatelliteDialog = () => {
  satelliteVisible.value = true
}

const saveSatellite = () => {
  if (!satelliteForm.value.name) {
    ElMessage.error('请输入卫星名称')
    return
  }
  
  // 保存到localStorage
  const satellites = JSON.parse(localStorage.getItem('satellites') || '[]')
  satellites.push(satelliteForm.value)
  localStorage.setItem('satellites', JSON.stringify(satellites))
  
  satelliteVisible.value = false
  outerVisible.value = false
  ElMessage.success('卫星保存成功')
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

const openGroundStationDialog = () => {
  groundStationVisible.value = true
}

const saveGroundStation = () => {
  if (!groundStationForm.value.name) {
    ElMessage.error('请输入地面站名称')
    return
  }
  
  // 保存到localStorage
  const groundStations = JSON.parse(localStorage.getItem('groundStations') || '[]')
  groundStations.push(groundStationForm.value)
  localStorage.setItem('groundStations', JSON.stringify(groundStations))
  
  groundStationVisible.value = false
  outerVisible.value = false
  ElMessage.success('地面站保存成功')
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

const areaTargetVisible = ref(false)
const areaTargetForm = ref({
  name: '',
  points: [
    {longitude: 116.4, latitude: 39.9},
    {longitude: 116.41, latitude: 39.9},
    {longitude: 116.41, latitude: 39.91}
  ],
  color: '#FF0000',
  description: ''
})

const openAreaTargetDialog = () => {
  areaTargetVisible.value = true
}

const addAreaPoint = () => {
  areaTargetForm.value.points.push({
    longitude: 116.4,
    latitude: 39.9
  })
}

const removeAreaPoint = (index) => {
  areaTargetForm.value.points.splice(index, 1)
}

const saveAreaTarget = () => {
  if (!areaTargetForm.value.name) {
    ElMessage.error('请输入区域名称')
    return
  }
  
  if (areaTargetForm.value.points.length < 3) {
    ElMessage.error('至少需要3个点坐标')
    return
  }

  // Check for duplicate points
  const uniquePoints = new Set()
  for (const point of areaTargetForm.value.points) {
    const key = `${point.longitude},${point.latitude}`
    if (uniquePoints.has(key)) {
      ElMessage.error('坐标点不能重复')
      return
    }
    uniquePoints.add(key)
  }

  // Save to localStorage
  const areaTargets = JSON.parse(localStorage.getItem('areaTargets') || '[]')
  areaTargets.push(areaTargetForm.value)
  localStorage.setItem('areaTargets', JSON.stringify(areaTargets))
  
  areaTargetVisible.value = false
  outerVisible.value = false
  ElMessage.success('区域目标保存成功')
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

const pointTargetVisible = ref(false)
const pointTargetForm = ref({
  name: '',
  longitude: 116.4,
  latitude: 39.9,
  height: 0,
  type: '',
  description: ''
})

const openPointTargetDialog = () => {
  pointTargetVisible.value = true
}

const savePointTarget = () => {
  if (!pointTargetForm.value.name) {
    ElMessage.error('请输入目标名称')
    return
  }
  
  if (!pointTargetForm.value.type) {
    ElMessage.error('请选择目标类型')
    return
  }

  // Save to localStorage
  const pointTargets = JSON.parse(localStorage.getItem('pointTargets') || '[]')
  pointTargets.push(pointTargetForm.value)
  localStorage.setItem('pointTargets', JSON.stringify(pointTargets))
  
  pointTargetVisible.value = false
  outerVisible.value = false
  ElMessage.success('地面目标保存成功')
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

const payloadVisible = ref(false)
const payloadForm = ref({
  name: '',
  satelliteId: '',
  type: '',
  fovType: 'cone',
  halfAngle: 45,
  description: ''
})

const payloadTypes = [
  { label: '光学', value: 'optical' },
  { label: '雷达', value: 'radar' },
  { label: '通信', value: 'communication' }
]

const fovTypes = [
  { label: '锥形', value: 'cone' },
  { label: '矩形', value: 'rectangle' },
  { label: '扇形', value: 'sector' }
]

const openPayloadDialog = () => {
  payloadVisible.value = true
}

const savePayload = () => {
  if (!payloadForm.value.name || !payloadForm.value.satelliteId || !payloadForm.value.type) {
    ElMessage.error('请填写完整的载荷信息')
    return
  }

  const payloads = JSON.parse(localStorage.getItem('payloads') || '[]')
  payloads.push({
    ...payloadForm.value,
    id: Date.now().toString()
  })
  localStorage.setItem('payloads', JSON.stringify(payloads))
  
  payloadVisible.value = false
  outerVisible.value = false
  ElMessage.success('载荷保存成功')
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

const showAndInit = () => {
  outerVisible.value = true
}

defineExpose({
  showAndInit,
})
</script>

<style lang="scss" scoped>
.custom-dialog {
  // 对话框整体样式
  :deep(.el-dialog) {
    border-radius: 12px;
    background: linear-gradient(145deg, #f8fafc, #f1f5f9);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
    
    // 标题样式
    .el-dialog__header {
      margin: 0;
      padding: 16px 20px;
      background: linear-gradient(90deg, #3b82f6, #6366f1);
      border-radius: 12px 12px 0 0;
      
      .el-dialog__title {
        color: white;
        font-size: 18px;
        font-weight: 600;
        letter-spacing: 1px;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
      }
      
      .el-dialog__headerbtn {
        top: 16px;
        right: 20px;
        
        .el-dialog__close {
          color: white;
          font-size: 20px;
        }
      }
    }
    
    // 内容区域样式
    .el-dialog__body {
      padding: 20px;
      background: linear-gradient(145deg, #f8fafc, #f1f5f9);
    }
    
    // 底部按钮区域样式
    .el-dialog__footer {
      padding: 16px 20px;
      background: #f8fafc;
      border-radius: 0 0 12px 12px;
      border-top: 1px solid #e2e8f0;
    }
  }
  
  // 按钮样式增强
  .dialog-buttons {
    .icon-button {
      background-color: white;
      border: 1px solid #e2e8f0;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        border-color: var(--el-color-primary);
      }
      
      .button-icon {
        transition: all 0.3s ease;
      }
      
      &:hover .button-icon {
        transform: scale(1.1);
        background-color: var(--el-color-primary);
        color: white;
      }
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .custom-dialog {
    :deep(.el-dialog) {
      width: 90% !important;
      margin-top: 5vh !important;
    }
  }
}
</style>
